﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "新增生产工单";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="mb-0">新增生产工单</h4>
                </div>
                <div class="card-body">
                    <form>
                        <!-- 基础信息 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="border-bottom pb-2 mb-3">基础信息</h5>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="orderCode" class="form-label">工单编号 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="OrderNumber" placeholder="请输入工单编号" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="orderName" class="form-label">工单名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="OrderName" placeholder="请输入工单名称">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="productionOrder" class="form-label">关联生产单号 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="Production_Number" placeholder="请选择生产单号" readonly>
                                        <button class="btn btn-outline-secondary" type="button" id="selectProductionOrder">
                                            <i class="fas fa-clipboard"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="project" class="form-label">关联项目</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="Related_Project" placeholder="请选择项目名称" readonly>
                                        <button class="btn btn-outline-secondary" type="button" id="selectProject">
                                            <i class="fas fa-folder"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="orderDate" class="form-label">工单日期</label>
                                    <div class="input-group">
                                        <input type="date" class="form-control" id="OrderDate">
                                        <button class="btn btn-outline-secondary" type="button" id="selectDate">
                                            <i class="fas fa-calendar"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="responsiblePerson" class="form-label">负责人</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="Principal" placeholder="请选择负责人" readonly>
                                        <button class="btn btn-outline-secondary" type="button" id="selectPerson">
                                            <i class="fas fa-user"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="department" class="form-label">所属部门</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="DepartmentName" placeholder="请选择部门" readonly>
                                        <button class="btn btn-outline-secondary" type="button" id="selectDepartment">
                                            <i class="fas fa-sitemap"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <div class="mb-3">
                                    <label for="remarks" class="form-label">备注</label>
                                    <textarea class="form-control" id="Note" rows="3" placeholder="请输入备注"></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- 生产物品 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="border-bottom pb-2 mb-3">生产物品</h5>
                            </div>
                            <!-- 左侧列 -->
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="ItemName" class="form-label">物品名称 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="ItemName" placeholder="请选择生产物品" readonly>
                                        <button class="btn btn-outline-secondary" type="button" id="selectItem"><i class="fas fa-cube"></i></button>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="SpecificationModel" class="form-label">规格型号</label>
                                    <input type="text" class="form-control" id="SpecificationModel" placeholder="请输入" readonly>
                                </div>
                                <div class="mb-3">
                                    <label for="ItemCategory" class="form-label">物品类别</label>
                                    <input type="text" class="form-control" id="ItemCategory" placeholder="请输入" readonly>
                                </div>
                                <div class="mb-3">
                                    <label for="PlanStartDate" class="form-label">计划开始时间</label>
                                    <div class="input-group">
                                        <input type="date" class="form-control" id="PlanStartDate">
                                        <button class="btn btn-outline-secondary" type="button" id="btnPlanStart"><i class="fas fa-calendar"></i></button>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="PlanQuantity" class="form-label">计划产量</label>
                                    <input type="number" class="form-control" id="PlanQuantity" placeholder="请输入计划生成量">
                                </div>
                            </div>
                            <!-- 右侧列 -->
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="ItemCode" class="form-label">物品编号</label>
                                    <input type="text" class="form-control" id="ItemCode" placeholder="请输入" readonly>
                                </div>
                                <div class="mb-3">
                                    <label for="Unit" class="form-label">单位</label>
                                    <input type="text" class="form-control" id="Unit" placeholder="请输入" readonly>
                                </div>
                                <div class="mb-3">
                                    <label for="ItemClass" class="form-label">物品分类</label>
                                    <input type="text" class="form-control" id="ItemClass" placeholder="请输入" readonly>
                                </div>
                                <div class="mb-3">
                                    <label for="PlanEndDate" class="form-label">计划结束时间</label>
                                    <div class="input-group">
                                        <input type="date" class="form-control" id="PlanEndDate">
                                        <button class="btn btn-outline-secondary" type="button" id="btnPlanEnd"><i class="fas fa-calendar"></i></button>
                                    </div>
                                </div>
                            </div>
                            <!-- 隐藏：生产单对应的 OrderId（用于物料查询） -->
                            <input type="hidden" id="Production_OrderId" value="">
                            <!-- 隐藏：选中的物品Id（来自 ArticleOutput.Id 或 id） -->
                            <input type="hidden" id="SelectedItemId" value="">
                        </div>

                        <!-- 工序流程 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="border-bottom pb-2 mb-3">工序流程</h5>
                                <div class="mb-3">
                                    <button type="button" class="btn btn-primary me-2" id="addProcess">
                                        <i class="fas fa-plus"></i> 添加
                                    </button>
                                    <button type="button" class="btn btn-warning" id="removeProcess">
                                        <i class="fas fa-minus"></i> 移除
                                    </button>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="processTable">
                                        <thead class="table-light">
                                            <tr>
                                                <th width="50">
                                                    <input type="checkbox" class="form-check-input" id="selectAllProcess">
                                                </th>
                                                <th width="80">序号</th>
                                                <th width="120">工序编码</th>
                                                <th width="150">工序名称</th>
                                                <th width="100">加工顺序</th>
                                                <th width="200">工艺流程</th>
                                                <th width="120">负责人</th>
                                                <th width="120">计划开始时间</th>
                                                <th width="120">计划结束时间</th>
                                                <th width="120">计划产量</th>
                                                <th width="150">备注</th>
                                                <th width="150">操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- 数据将通过JavaScript动态填充 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="row">
                            <div class="col-12 text-center">
                                <button type="button" class="btn btn-primary me-2" id="saveWorkOrder">
                                    <i class="fas fa-save"></i> 保存
                                </button>
                                <button type="button" class="btn btn-secondary me-2" onclick="history.back()">
                                    <i class="fas fa-arrow-left"></i> 返回
                                </button>
                                <button type="button" class="btn btn-outline-secondary" id="resetForm">
                                    <i class="fas fa-undo"></i> 重置
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 选择生产单号模态框 -->
<div class="modal fade" id="productionOrderModal" tabindex="-1" aria-labelledby="productionOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="productionOrderModalLabel">选择生产单号</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
                         <div class="modal-body">
                
                                 <!-- 数据表格 -->
                 <div class="table-responsive">
                     <table class="table table-bordered table-hover" id="productionOrderTable">
                         <thead class="table-light">
                             <tr>
                                 <th width="50">选择</th>
                                 <th width="80">序号</th>
                                 <th width="150">生产单号</th>
                                 <th width="200">生产主题</th>
                                 <th width="120">单据日期</th>
                                 <th width="100">负责人</th>
                                 <th width="120">所在部门</th>
                                 <th width="120">关联项目</th>
                             </tr>
                         </thead>
                         <tbody>
                             <!-- 数据将通过JavaScript动态填充 -->
                         </tbody>
                     </table>
                 </div>
                
                
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmProductionOrder">确定</button>
            </div>
        </div>
    </div>
</div>
                   
<!-- 选择物品模态框 -->
<div class="modal fade" id="itemSelectModal" tabindex="-1" aria-labelledby="itemSelectModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="itemSelectModalLabel">选择物品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 查询条件 -->
                <div class="row g-2 mb-3">
                    <div class="col-md-4">
                        <input type="text" id="filterArticle" class="form-control" placeholder="请输入物品编号/名称/规格型号">
                    </div>
                    <div class="col-md-3">
                        <select id="filterArticleType" class="form-select">
                            <option value="">选择物品类别</option>
                            <option value="原材料">原材料</option>
                            <option value="半成品">半成品</option>
                            <option value="成品">成品</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select id="filterClassification" class="form-select">
                            <option value="">物品分类</option>
                            <option value="电子产品">电子产品</option>
                            <option value="家具">家具</option>
                            <option value="食品">食品</option>
                            <option value="化妆品">化妆品</option>
                            <option value="生活用品">生活用品</option>
                        </select>
                    </div>
                    <div class="col-md-2 text-end">
                        <button id="btnSearchItem" class="btn btn-primary">查询</button>
                        <button id="btnResetItem" class="btn btn-outline-secondary ms-1">重置</button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="itemTable">
                        <thead class="table-light">
                            <tr>
                                <th width="50">选择</th>
                                <th width="140">物品编号</th>
                                <th>物品名称</th>
                                <th width="140">规格型号</th>
                                <th width="100">单位</th>
                                <th width="120">物品类别</th>
                                <th width="140">物品分类</th>
                                <th width="120">品牌</th>
                                <th width="100">总库存</th>
                                <th width="130">采购单价价格</th>
                                <th width="130">销售单价价格</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
                <!-- 分页 -->
                <div class="d-flex justify-content-between align-items-center mt-2">
                    <div>
                        <span id="itemPagerInfo"></span>
                    </div>
                    <div class="btn-group">
                        <button class="btn btn-outline-secondary" id="itemPrev">上一页</button>
                        <button class="btn btn-outline-secondary" id="itemNext">下一页</button>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmItem">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- 选择工序流程模态框 -->
<div class="modal fade" id="processSelectModal" tabindex="-1" aria-labelledby="processSelectModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="processSelectModalLabel">选择工序流程</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="processSelectTable">
                        <thead class="table-light">
                            <tr>
                                <th width="50">选择</th>
                                <th width="80">序号</th>
                                <th width="120">工序编码</th>
                                <th width="150">工序名称</th>
                                <th width="100">加工顺序</th>
                                <th width="200">工艺流程</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmProcess">确定</button>
            </div>
        </div>
    </div>
</div>
                

<style>
    .form-control-sm {
        font-size: 0.875rem;
        padding: 0.25rem 0.5rem;
    }
    
    .form-select-sm {
        font-size: 0.875rem;
        padding: 0.25rem 0.5rem;
    }
    
    .btn-sm {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
    }
    
    .table th {
        font-size: 0.875rem;
        font-weight: 600;
        background-color: #f8f9fa;
    }
    
    .table td {
        vertical-align: middle;
    }
    
    .border-bottom {
        border-bottom: 2px solid #dee2e6 !important;
    }
    /* 放大物品弹窗内表格布局，避免换行挤压 */
    #itemSelectModal .table th,
    #itemSelectModal .table td {
        white-space: nowrap;
    }
</style>

<script>
    let processCounter = 6; // 从6开始，因为已有5行数据

    // 页面加载时自动生成工单编号
    document.addEventListener('DOMContentLoaded', function() {
        generateOrderCode();
        setCurrentDate();
    });

    // 生成工单编号：SCGDBH + 年月日时分秒
    function generateOrderCode() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        
        const orderCode = `SCGDBH${year}${month}${day}${hours}${minutes}${seconds}`;
        document.getElementById('OrderNumber').value = orderCode;
    }

    // 设置当前日期
    function setCurrentDate() {
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('OrderDate').value = today;
    }

    // 关联项目选择事件
    document.getElementById('selectProject').addEventListener('click', function() {
        // 这里可以打开项目选择弹窗或跳转到项目选择页面
        // 暂时使用示例数据
        const projectInput = document.getElementById('Related_Project');
        const projects = ['项目A', '项目B', '项目C', '项目D', '项目E'];
        const randomProject = projects[Math.floor(Math.random() * projects.length)];
        projectInput.value = randomProject;
    });

    // 关联生产单号选择事件
    document.getElementById('selectProductionOrder').addEventListener('click', function() {
        // 调用后端API获取生产单号数据
        loadProductionOrders();
        // 显示选择生产单号模态框
        const modal = new bootstrap.Modal(document.getElementById('productionOrderModal'));
        modal.show();
    });

    // 加载生产单号数据
    async function loadProductionOrders() {
        try {
            console.log('开始调用API...');
            const response = await fetch('http://localhost:5299/api/WorkOrder/GetProductionOrder');
            console.log('API响应状态:', response.status);
            
            if (response.ok) {
                const result = await response.json();
                console.log('API响应数据:', result);
                
                // 根据API响应结构，提取data数组
                if (result.data && Array.isArray(result.data)) {
                    console.log('找到数据数组，长度:', result.data.length);
                    populateProductionOrderTable(result.data);
                } else {
                    console.error('API返回数据格式不正确:', result);
                    console.log('使用默认数据');
                    populateProductionOrderTable(getDefaultProductionOrders());
                }
            } else {
                console.error('获取生产单号数据失败:', response.statusText);
                console.log('使用默认数据');
                populateProductionOrderTable(getDefaultProductionOrders());
            }
        } catch (error) {
            console.error('API调用错误:', error);
            console.log('使用默认数据');
            populateProductionOrderTable(getDefaultProductionOrders());
        }
    }

    // 物品选择按钮：要求已选生产单号
    document.getElementById('selectItem').addEventListener('click', async function () {
        // 直接选择物品，不再强制先选生产单号
        window.itemPageIndex = 1;
        await queryAndRenderItems();
        const modal = new bootstrap.Modal(document.getElementById('itemSelectModal'));
        modal.show();
    });

    // 查询与渲染物品（调用后端 GetArticleOutput）
    async function queryAndRenderItems() {
        // 物品与生产单号无关：完全不携带 OrderId
        const keyword = document.getElementById('filterArticle').value.trim();
        const articleType = document.getElementById('filterArticleType').value;
        const classification = document.getElementById('filterClassification').value;
        const pageIndex = window.itemPageIndex || 1;
        const pageSize = 10;

        // 仅在有值时才携带筛选项，避免空字符串导致后端当作精确筛选
        const queryObj = {
            // 明确告诉后端：不根据订单过滤
            OrderId: '',
            PageIndex: String(pageIndex),
            PageSize: String(pageSize),
            _ts: String(Date.now())
        };
        if (keyword) queryObj.ArticleNumber = keyword;
        if (articleType) queryObj.ArticleType = articleType;
        if (classification) queryObj.Classification = classification;
        const query = new URLSearchParams(queryObj);

        try {
            // 若后端依然要求 OrderId，可在接口层放宽。这里确保我们不传 OrderId
            let url = `http://localhost:5299/api/WorkOrder/GetArticleOutput?${query.toString()}`;
            console.log('加载物品列表 URL =>', url);
            let resp = await fetch(url, { cache: 'no-store' });
            if (!resp.ok) throw new Error(resp.statusText);
            let res = await resp.json();
            let rows = Array.isArray(res?.pageData) ? res.pageData : Array.isArray(res?.data) ? res.data : [];

            // 无筛选条件且结果为空时，尝试无参重试一次（兼容后端把空参数当严格过滤）
            const noFilters = !keyword && !articleType && !classification;
            if (noFilters && rows.length === 0) {
                const retryUrl = `http://localhost:5299/api/WorkOrder/GetArticleOutput?_ts=${Date.now()}`;
                console.warn('物品列表为空，尝试无参重试 =>', retryUrl);
                resp = await fetch(retryUrl, { cache: 'no-store' });
                if (resp.ok) {
                    res = await resp.json();
                    rows = Array.isArray(res?.pageData) ? res.pageData : Array.isArray(res?.data) ? res.data : [];
                }
            }
            populateItemTable(rows);
            const total = Number(res?.totalCount || rows.length);
            const totalPage = Math.max(1, Math.ceil(total / pageSize));
            document.getElementById('itemPagerInfo').textContent = `第 ${pageIndex} / ${totalPage} 页，共 ${total} 条`;
            window.itemTotalPage = totalPage;
        } catch (e) {
            console.error('获取物品失败:', e);
            populateItemTable([]);
            document.getElementById('itemPagerInfo').textContent = '没有数据';
        }
    }

    function extractOrderIdFromProductionNo(productionNo) {
        // 若生产单号直接就是 OrderId 则直接返回；
        // 否则可在此做映射解析，这里尝试提取末尾数字
        const id = parseInt(productionNo.replace(/\D+/g, ''), 10);
        return Number.isFinite(id) ? id : productionNo;
    }

    function populateItemTable(items) {
        // 使用全新的 tbody 替换旧的，避免重复监听且不丢数据
        const oldTbody = document.querySelector('#itemTable tbody');
        const newTbody = oldTbody.cloneNode(false);
        oldTbody.parentNode.replaceChild(newTbody, oldTbody);

        items.forEach((x, idx) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><input type=\"radio\" name=\"selectedItem\" value=\"${idx}\" data-item='${JSON.stringify(x)}'></td>
                <td>${x.articleNumber || ''}</td>
                <td>${x.articleName || ''}</td>
                <td>${x.specifications || ''}</td>
                <td>${x.unitName || ''}</td>
                <td>${x.articleType || ''}</td>
                <td>${x.classification || ''}</td>
                <td>${x.brand || ''}</td>
                <td>${x.total_Inventory ?? ''}</td>
                <td>${x.unit_Price ?? ''}</td>
                <td>${x.sale_Price ?? ''}</td>
            `;
            tr.dataset.item = JSON.stringify(x);
            newTbody.appendChild(tr);
        });

        // 行点击选中并立即回填（不依赖单选框是否存在）
        newTbody.addEventListener('click', function (e) {
            const row = e.target.closest('tr');
            if (!row) return;
            const radio = row.querySelector('input[name="selectedItem"]');
            if (radio) radio.checked = true;
            let data;
            try { data = JSON.parse(row.dataset.item || '{}'); } catch { data = {}; }
            window.lastSelectedArticle = data;
            window.fillSelectedItem(data);
        });

        // 选中单选框时立即回填（不等点击确定），最直观也最稳妥
        newTbody.addEventListener('change', function (e) {
            const target = e.target;
            if (target && target.name === 'selectedItem') {
                let data;
                try { data = JSON.parse(target.getAttribute('data-item') || '{}'); } catch { data = {}; }
                window.lastSelectedArticle = data;
                try { alert(`已选中物品: ${data.articleName || ''}`); } catch {}
                window.fillSelectedItem(data);
            }
        });

        // 行双击直接填充并关闭
        newTbody.addEventListener('dblclick', function (e) {
            const row = e.target.closest('tr');
            if (!row) return;
            let data; try { data = JSON.parse(row.dataset.item || '{}'); } catch { data = {}; }
            window.lastSelectedArticle = data;
            window.fillSelectedItem(data);
            const modalEl = document.getElementById('itemSelectModal');
            const modal = bootstrap.Modal.getInstance(modalEl);
            if (modal) {
                modal.hide();
                // 等模态框隐藏动画结束后再二次写入，确保节点可写
                modalEl.addEventListener('hidden.bs.modal', function once() {
                    modalEl.removeEventListener('hidden.bs.modal', once);
                    window.fillSelectedItem(data);
                });
            }
        });

        // 模仿“选择生产单号”的使用体验：支持在表格中选中后按回车键直接确认
        newTbody.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                const current = e.target.closest('tr');
                if (!current) return;
                let data; try { data = JSON.parse(current.dataset.item || '{}'); } catch { data = {}; }
                window.lastSelectedArticle = data;
                window.fillSelectedItem(data);
                const modalEl = document.getElementById('itemSelectModal');
                const modal = bootstrap.Modal.getInstance(modalEl);
                if (modal) {
                    modal.hide();
                    modalEl.addEventListener('hidden.bs.modal', function once() {
                        modalEl.removeEventListener('hidden.bs.modal', once);
                        window.fillSelectedItem(data);
                    });
                }
            }
        });
    }

    // 条件查询、重置、分页
    document.getElementById('btnSearchItem').addEventListener('click', async function (e) {
        e.preventDefault();
        window.itemPageIndex = 1;
        await queryAndRenderItems();
    });
    document.getElementById('btnResetItem').addEventListener('click', async function (e) {
        e.preventDefault();
        document.getElementById('filterArticle').value = '';
        document.getElementById('filterArticleType').value = '';
        document.getElementById('filterClassification').value = '';
        window.itemPageIndex = 1;
        await queryAndRenderItems();
    });
    document.getElementById('itemPrev').addEventListener('click', async function () {
        if ((window.itemPageIndex || 1) > 1) {
            window.itemPageIndex--;
            await queryAndRenderItems();
        }
    });
    document.getElementById('itemNext').addEventListener('click', async function () {
        const total = window.itemTotalPage || 1;
        if ((window.itemPageIndex || 1) < total) {
            window.itemPageIndex++;
            await queryAndRenderItems();
        }
    });

    // 将 setInputValue 直接挂载到全局作用域
    window.setInputValue = function(idOrIds, value) {
        const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
        let el = null;
        for (const id of ids) {
            el = document.getElementById(id) || document.querySelector(`[name="${id}"]`);
            if (el) break;
        }
        if (!el) return;
        const v = value ?? '';
        // 原生赋值
        el.value = v;
        // jQuery 赋值（若存在）
        try { if (window.$) { window.$(el).val(v).trigger('input').trigger('change'); } } catch {}
        // 派发事件（双保）
        try { el.dispatchEvent(new Event('input', { bubbles: true })); } catch {}
        try { el.dispatchEvent(new Event('change', { bubbles: true })); } catch {}
    };

    // 将 fillSelectedItem 直接挂载到全局作用域
    window.fillSelectedItem = function(data) {
        // 直接使用 ArticleOutput 字段映射 + 触发变更事件，确保双向绑定/校验能感知
        window.setInputValue(['ItemName','itemName'], data.articleName || '');
        window.setInputValue(['ItemCode','itemCode'], data.articleNumber || '');
        window.setInputValue(['SpecificationModel','specifications','spec'], data.specifications || '');
        window.setInputValue(['Unit','unit'], data.unitName || '');
        window.setInputValue(['ItemCategory','category','articleType'], data.articleType || '');
        window.setInputValue(['ItemClass','className','classification'], data.classification || '');
        // 记录选中的物品Id
        window.setInputValue(['SelectedItemId','itemId','Id'], data.Id || data.id || '');

        // 再补一次（延迟到模态框完全关闭后），避免焦点/aria-hidden 干扰
        setTimeout(() => {
            window.setInputValue(['ItemName','itemName'], data.articleName || '');
            window.setInputValue(['ItemCode','itemCode'], data.articleNumber || '');
            window.setInputValue(['SpecificationModel','specifications','spec'], data.specifications || '');
            window.setInputValue(['Unit','unit'], data.unitName || '');
            window.setInputValue(['ItemCategory','category','articleType'], data.articleType || '');
            window.setInputValue(['ItemClass','className','classification'], data.classification || '');
            window.setInputValue(['SelectedItemId','itemId','Id'], data.Id || data.id || '');
            console.log('[ItemSelect] 二次写入已完成');
        }, 80);
    };

    // 初始化全局变量
    window.lastSelectedArticle = window.lastSelectedArticle || null;

    // 确认物品（事件委托，避免绑定失败）
    document.addEventListener('click', function (e) {
        if (!e.target.closest || !e.target.closest('#confirmItem')) return;
        console.log('[ItemSelect] 点击确定');
        // 严格参照选择生产单号的实现：从选中单选框的 data-item 读取
        let data = null;
        const selected = document.querySelector('#itemTable tbody input[name="selectedItem"]:checked');
        if (selected) {
            try { data = JSON.parse(selected.getAttribute('data-item') || '{}'); } catch { data = {}; }
        }
        if (!data || Object.keys(data).length === 0) {
            // 若不存在单选框或未选中，使用最后一次点击行的数据
            if (window.lastSelectedArticle) {
                data = window.lastSelectedArticle;
            } else {
                // 再兜底取第一行
                const firstRow = document.querySelector('#itemTable tbody tr');
                if (!firstRow) { alert('没有可选择的物品'); return; }
                try { data = JSON.parse(firstRow.dataset.item || '{}'); } catch { data = {}; }
            }
        }
        try { alert(`确定选择: ${data.articleName || ''}`); } catch {}
        console.log('[ItemSelect] 选中数据 =>', data);
        window.fillSelectedItem(data);

        const modalEl = document.getElementById('itemSelectModal');
        const modal = bootstrap.Modal.getInstance(modalEl);
        if (modal) {
            modal.hide();
            modalEl.addEventListener('hidden.bs.modal', function once() {
                modalEl.removeEventListener('hidden.bs.modal', once);
                window.fillSelectedItem(data);
            });
        }
    });

    // 确认选择工序
    document.getElementById('confirmProcess').addEventListener('click', async function() {
        const selectedRadio = document.querySelector('input[name="selectedProcess"]:checked');
        if (selectedRadio) {
            // 获取选中的完整数据对象
            const selectedData = JSON.parse(selectedRadio.getAttribute('data-item'));
            console.log('选中的工序数据:', selectedData);

            // 若无ID，尝试立即通过工序编号解析ID并回填
            let currentId = selectedData.id ?? selectedData.Id ?? selectedData.activity_Id ?? selectedData.Activity_Id ?? '';
            if (!currentId && (selectedData.activity_ListNumber || selectedData.Activity_ListNumber)) {
                const number = selectedData.activity_ListNumber || selectedData.Activity_ListNumber;
                try {
                    const fixedId = await resolveActivityIdByNumber(number);
                    if (fixedId) {
                        selectedData.Activity_Id = fixedId;
                        currentId = fixedId;
                        console.log('[ProcessSelect] 解析得到的 Activity_Id:', fixedId);
                    } else {
                        console.warn('[ProcessSelect] 未能解析到 Activity_Id, number =', number);
                    }
                } catch (e) {
                    console.warn('[ProcessSelect] 解析 Activity_Id 异常:', e);
                }
            }

            // 添加工序到主表格
            addProcessToTable(selectedData);

            // 立即打印一遍当前第一行 activity_Id，用于验证
            const firstRowHidden = document.querySelector('#processTable tbody tr input.activity-id');
            console.log('[ProcessSelect] 添加后首行 activity_Id =', firstRowHidden ? firstRowHidden.value : '(未找到)');

            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('processSelectModal'));
            modal.hide();
        } else {
            alert('请选择一个工序');
        }
    });


    // 填充生产单号表格
    function populateProductionOrderTable(data) {
        console.log('开始填充表格，数据:', data);
        const tbody = document.querySelector('#productionOrderTable tbody');
        if (!tbody) {
            console.error('找不到表格tbody元素');
            return;
        }
        
        tbody.innerHTML = '';
        
        // 根据API实际返回的字段名称进行映射
        data.forEach((item, index) => {
            console.log('处理数据项:', item);
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><input type="radio" name="selectedProductionOrder" value="${item.productionOrderNumber || ''}" data-item='${JSON.stringify(item)}'></td>
                <td>${index + 1}</td>
                <td>${item.productionOrderNumber || ''}</td>
                <td>${item.production_Theme || ''}</td>
                <td>${item.bill_Date ? item.bill_Date.split('T')[0] : ''}</td>
                <td>${item.task_Leader || ''}</td>
                <td>${item.team_Name || ''}</td>
                <td>${item.related_Roject || ''}</td>
            `;
            tbody.appendChild(row);
        });
        
        console.log('表格填充完成，行数:', tbody.children.length);
    }

    // 默认生产单号数据（API失败时的备用数据）
    function getDefaultProductionOrders() {
        return [
            {
                productionOrderNumber: 'PO-2024-001',
                production_Theme: '智能手机外壳设计变更',
                bill_Date: '2024-06-01',
                task_Leader: '张伟',
                team_Name: '设计部',
                related_Roject: '智能手机项目'
            },
            {
                productionOrderNumber: 'PO-2024-002',
                production_Theme: '电视显示屏原材料采购',
                bill_Date: '2024-06-02',
                task_Leader: '李娜',
                team_Name: '采购部',
                related_Roject: '电视显示屏项目'
            }
        ];
    }

   

    // 确认选择生产单号
    document.getElementById('confirmProductionOrder').addEventListener('click', function() {
        const selectedRadio = document.querySelector('input[name="selectedProductionOrder"]:checked');
        if (selectedRadio) {
            // 获取选中的完整数据对象
            const selectedData = JSON.parse(selectedRadio.getAttribute('data-item'));
            console.log('选中的数据:', selectedData);
            
            // 填充关联生产单号
            const productionOrderInput = document.getElementById('Production_Number');
            productionOrderInput.value = selectedData.productionOrderNumber || '';
            
            // 填充关联项目
            const projectInput = document.getElementById('Related_Project');
            projectInput.value = selectedData.related_Roject || '';
            
            // 填充负责人
            const responsiblePersonInput = document.getElementById('Principal');
            responsiblePersonInput.value = selectedData.task_Leader || '';
            
            // 填充所属部门
            const departmentInput = document.getElementById('DepartmentName');
            departmentInput.value = selectedData.team_Name || '';
            
            // 存储OrderId（若后端返回该字段时）
            if (selectedData.orderId) {
                document.getElementById('Production_OrderId').value = selectedData.orderId;
            }
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('productionOrderModal'));
            modal.hide();
        } else {
            alert('请选择一个生产单号');
        }
    });



    // 全选功能
    document.getElementById('selectAllProcess').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.process-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // 添加工序 - 打开工序选择模态框
    document.getElementById('addProcess').addEventListener('click', function() {
        // 加载工序数据并显示模态框
        loadProcessData();
        const modal = new bootstrap.Modal(document.getElementById('processSelectModal'));
        modal.show();
    });

    // 移除工序
    document.getElementById('removeProcess').addEventListener('click', function() {
        const selectedRows = document.querySelectorAll('.process-checkbox:checked');
        if (selectedRows.length === 0) {
            alert('请选择要移除的工序');
            return;
        }
        
        selectedRows.forEach(checkbox => {
            const row = checkbox.closest('tr');
            row.remove();
        });
        
        updateSequenceNumbers();
    });

    // 上移
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('move-up')) {
            const row = e.target.closest('tr');
            const prevRow = row.previousElementSibling;
            if (prevRow) {
                row.parentNode.insertBefore(row, prevRow);
                updateSequenceNumbers();
            }
        }
    });

    // 下移
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('move-down')) {
            const row = e.target.closest('tr');
            const nextRow = row.nextElementSibling;
            if (nextRow) {
                row.parentNode.insertBefore(nextRow, row);
                updateSequenceNumbers();
            }
        }
    });

    // 移除单行
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-row')) {
            const row = e.target.closest('tr');
            row.remove();
            updateSequenceNumbers();
        }
    });

    // 更新序号
    function updateSequenceNumbers() {
        const rows = document.querySelectorAll('#processTable tbody tr');
        rows.forEach((row, index) => {
            const sequenceCell = row.cells[1];
            const orderInput = row.cells[5].querySelector('input');
            sequenceCell.textContent = index + 1;
            if (orderInput) {
            orderInput.value = index + 1;
            }
        });
        processCounter = rows.length + 1;
    }

    // 加载工序数据
    async function loadProcessData() {
        try {
            console.log('开始加载工序数据...');
            const response = await fetch('http://localhost:5299/api/WorkOrder/GetActivity_ListOutput');
            console.log('工序API响应状态:', response.status);
            
            if (response.ok) {
                const result = await response.json();
                console.log('工序API响应数据:', result);
                
                // 根据API响应结构，提取pageData数组
                if (result.pageData && Array.isArray(result.pageData)) {
                    console.log('找到工序数据数组，长度:', result.pageData.length);
                    populateProcessSelectTable(result.pageData);
                } else {
                    console.error('工序API返回数据格式不正确:', result);
                    console.log('使用默认工序数据');
                    populateProcessSelectTable(getDefaultProcessData());
                }
            } else {
                console.error('获取工序数据失败:', response.statusText);
                console.log('使用默认工序数据');
                populateProcessSelectTable(getDefaultProcessData());
            }
        } catch (error) {
            console.error('工序API调用错误:', error);
            console.log('使用默认工序数据');
            populateProcessSelectTable(getDefaultProcessData());
        }
    }

    // 填充工序选择表格
    function populateProcessSelectTable(data) {
        console.log('开始填充工序表格，数据:', data);
        const tbody = document.querySelector('#processSelectTable tbody');
        if (!tbody) {
            console.error('找不到工序表格tbody元素');
            return;
        }
        
        tbody.innerHTML = '';
        
        // 根据API实际返回的字段名称进行映射
        data.forEach((item, index) => {
            console.log('处理工序数据项:', item);
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><input type="radio" name="selectedProcess" value="${item.activity_ListNumber || ''}" data-item='${JSON.stringify(item)}'></td>
                <td>${index + 1}</td>
                <td>${item.activity_ListNumber || ''}</td>
                <td>${item.activity_ListName || ''}</td>
                <td>${item.processing || ''}</td>
                <td>${item.process_Name || ''}</td>
            `;
            tbody.appendChild(row);
        });
        
        console.log('工序表格填充完成，行数:', tbody.children.length);
    }

    // 默认工序数据（API失败时的备用数据）
    function getDefaultProcessData() {
        return [
            {
                activity_ListNumber: 'GXBH20250903',
                activity_ListName: '原材料检验',
                processing: 1,
                process_Name: '牙膏管加工流程'
            },
            {
                activity_ListNumber: 'GXBH20250904',
                activity_ListName: '切割加工',
                processing: 2,
                process_Name: '精密切割加工流程'
            },
            {
                activity_ListNumber: 'GXBH20250905',
                activity_ListName: '组装工序',
                processing: 3,
                process_Name: '自动化组装流程'
            },
            {
                activity_ListNumber: 'GXBH20250906',
                activity_ListName: '质量检测',
                processing: 4,
                process_Name: '质量检测流程'
            },
            {
                activity_ListNumber: 'GXBH20250907',
                activity_ListName: '包装入库',
                processing: 5,
                process_Name: '包装入库流程'
            }
        ];
    }

    // 添加工序到主表格
    function addProcessToTable(processData) {
        const tbody = document.querySelector('#processTable tbody');
        const newRow = document.createElement('tr');
        const activityId = (processData.id ?? processData.Id ?? processData.activity_Id ?? processData.Activity_Id ?? '').toString();
        newRow.innerHTML = `
            <td><input type="checkbox" class="form-check-input process-checkbox"></td>
            <td>${processCounter}</td>
            <td style="display:none"><input type="hidden" class="activity-id" value="${processData.id ?? processData.Id ?? processData.activity_Id ?? processData.Activity_Id ?? ''}"></td>
            <td>
                <div class="d-flex align-items-center">
                    <input type="text" class="form-control form-control-sm" value="${processData.activity_ListNumber || ''}" readonly>
                    <span class="ms-2 badge bg-secondary">ID: ${activityId}</span>
                </div>
            </td>
            <td><input type="text" class="form-control form-control-sm" value="${processData.activity_ListName || ''}" readonly></td>
            <td><input type="number" class="form-control form-control-sm" value="${processData.processing || processCounter}"></td>
            <td><input type="text" class="form-control form-control-sm" value="${processData.process_Name || ''}" readonly></td>
            <td>
                <select class="form-select form-select-sm">
                    <option value="">请选择负责人</option>
                    <option value="张三">张三</option>
                    <option value="李四">李四</option>
                    <option value="王五">王五</option>
                    <option value="赵六">赵六</option>
                    <option value="钱七">钱七</option>
                </select>
            </td>
            <td><input type="date" class="form-control form-control-sm"></td>
            <td><input type="date" class="form-control form-control-sm"></td>
            <td><input type="number" class="form-control form-control-sm" placeholder="计划产量"></td>
            <td><input type="text" class="form-control form-control-sm" placeholder="备注"></td>
            <td>
                <button type="button" class="btn btn-sm btn-outline-secondary move-up">上移</button>
                <button type="button" class="btn btn-sm btn-outline-secondary move-down">下移</button>
                <button type="button" class="btn btn-sm btn-outline-danger remove-row">移除</button>
            </td>
        `;
        tbody.appendChild(newRow);
        // 如果没有携带ID，尝试通过工序编号回填
        if (!activityId && processData.activity_ListNumber) {
            resolveActivityIdByNumber(processData.activity_ListNumber).then((fixedId) => {
                if (fixedId) {
                    const hidden = newRow.querySelector('input.activity-id');
                    if (hidden) hidden.value = fixedId;
                    const idBadge = newRow.querySelector('.badge');
                    if (idBadge) idBadge.textContent = `ID: ${fixedId}`;
                }
            }).catch(() => {});
        }
        processCounter++;
        updateSequenceNumbers();
    }

    // 收集表单数据
    function collectFormData() {
        // 基础信息
        const orderNumber = document.getElementById('OrderNumber').value;
        const orderName = document.getElementById('OrderName').value;
        const productionNumber = document.getElementById('Production_Number').value;
        const relatedProject = document.getElementById('Related_Project').value;
        const orderDate = document.getElementById('OrderDate').value;
        const principal = document.getElementById('Principal').value;
        const departmentName = document.getElementById('DepartmentName').value;
        const note = document.getElementById('Note').value;

        // 生产物品信息
        const itemName = document.getElementById('ItemName').value;
        const itemCode = document.getElementById('ItemCode').value;
        const specificationModel = document.getElementById('SpecificationModel').value;
        const unit = document.getElementById('Unit').value;
        const itemCategory = document.getElementById('ItemCategory').value;
        const itemClass = document.getElementById('ItemClass').value;
        const planStartDate = document.getElementById('PlanStartDate').value;
        const planEndDate = document.getElementById('PlanEndDate').value;
        const planQuantity = document.getElementById('PlanQuantity').value;
        const selectedItemId = document.getElementById('SelectedItemId').value;
        const productionOrderId = document.getElementById('Production_OrderId').value;

        // 收集工序流程数据
        const processRows = document.querySelectorAll('#processTable tbody tr');
        const processData = [];
        
        processRows.forEach((row, index) => {
            const cells = row.cells;
            if (cells.length >= 12) {
                const process = {
                    Activity_Id: parseInt((row.querySelector('input.activity-id')?.value || '0'), 10) || 0,
                    Activity_ListNumber: cells[3].querySelector('input').value,
                    Activity_ListName: cells[4].querySelector('input').value,
                    Processing: parseInt(cells[5].querySelector('input').value) || (index + 1),
                    Process_Name: cells[6].querySelector('input').value,
                    Principal: cells[7].querySelector('select').value,
                    Planned_Start: cells[8].querySelector('input').value,
                    Planned_Completion: cells[9].querySelector('input').value,
                    Planned_Output: parseInt(cells[10].querySelector('input').value) || 0,
                    Note: cells[11].querySelector('input').value
                };
                processData.push(process);
            }
        });

        // 构建API请求数据 - 根据最新API结构调整字段映射
        const requestData = {
            orderNumber: orderNumber || "",
            orderName: orderName || "",
            production_Number: productionNumber || "", // 使用生产单号字符串
            related_Project: relatedProject || "",
            orderDate: orderDate ? new Date(orderDate).toISOString() : new Date().toISOString(),
            principal: principal || "",
            departmentName: departmentName || "",
            status: "待开始",
            note: note || "",
            // 物品相关字段
            articleNumber: itemCode || "",
            article_Id: parseInt(selectedItemId) || 0,
            articleName: itemName || "",
            specifications: specificationModel || "",
            unitName: unit || "",
            articleType: itemCategory || "",
            classification: itemClass || "",
            brand: "",
            total_Inventory: 0,
            unit_Price: 0,
            sale_Price: 0,
            orderId: parseInt(selectedItemId) || 0,
            planned_Start: planStartDate ? new Date(planStartDate).toISOString() : null,
            planned_Completion: planEndDate ? new Date(planEndDate).toISOString() : null,
            planned_Output: parseInt(planQuantity) || 0,
            qualifiedNum: 0,
            disqualificationNum: 0,
            pass: "未检测",
            // 工序流程数据（如果有多个工序，这里只取第一个，实际项目中可能需要调整）
            activity_Id: processData.length > 0 ? (parseInt(processData[0].Activity_Id, 10) || 0) : 0,
            activity_ListNumber: processData.length > 0 ? processData[0].Activity_ListNumber : "",
            activity_ListName: processData.length > 0 ? processData[0].Activity_ListName : "",
            processing: processData.length > 0 ? processData[0].Processing : 0,
            process_Name: processData.length > 0 ? processData[0].Process_Name : "",
            Principal: processData.length > 0 ? processData[0].Principal : "",
            Planned_Start: processData.length > 0 ? (processData[0].Planned_Start ? new Date(processData[0].Planned_Start).toISOString() : null) : null,
            Planned_Completion: processData.length > 0 ? (processData[0].Planned_Completion ? new Date(processData[0].Planned_Completion).toISOString() : null) : null,
            Planned_Output: processData.length > 0 ? processData[0].Planned_Output : 0,
            Note: processData.length > 0 ? processData[0].Note : "",
            state: "待开始",
            completed: 0
        };

        return requestData;
    }

    // 保存工单
    async function saveWorkOrder() {
        try {
            // 收集表单数据
            const formData = collectFormData();

            // 若缺少 activity_Id，尝试通过工序编码回填
            if ((!formData.activity_Id || Number(formData.activity_Id) === 0) && formData.activity_ListNumber) {
                try {
                    const fixedId = await resolveActivityIdByNumber(formData.activity_ListNumber);
                    if (fixedId) {
                        formData.activity_Id = fixedId;
                    }
                } catch (e) { console.warn('回填 activity_Id 失败:', e); }
            }
            
            // 验证必填字段
            if (!formData.orderNumber || !formData.orderName || !formData.articleName || !formData.articleNumber) {
                alert('请填写必填字段：工单编号、工单名称、物品名称、物品编号');
                return;
            }
            
            // 验证物品信息是否完整
            if (!formData.article_Id || formData.article_Id === 0) {
                alert('请先选择生产物品！');
                return;
            }
            
            // 验证计划信息
            if (!formData.planned_Start || !formData.planned_Completion || !formData.planned_Output) {
                alert('请填写完整的计划信息：计划开始时间、计划结束时间、计划产量');
                return;
            }

            console.log('准备提交的数据:', formData);
            console.log('关键字段信息:', {
                production_Number: formData.production_Number,
                article_Id: formData.article_Id,
                articleNumber: formData.articleNumber,
                articleName: formData.articleName,
                activity_Id: formData.activity_Id,
                activity_ListNumber: formData.activity_ListNumber,
                activity_ListName: formData.activity_ListName,
                Principal: formData.Principal,
                Planned_Start: formData.Planned_Start,
                Planned_Completion: formData.Planned_Completion,
                Planned_Output: formData.Planned_Output,
                planned_Start: formData.planned_Start,
                planned_Completion: formData.planned_Completion,
                planned_Output: formData.planned_Output
            });

            // 显示加载状态
            const saveBtn = document.getElementById('saveWorkOrder');
            const originalText = saveBtn.innerHTML;
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
            saveBtn.disabled = true;

            // 调用API
            const response = await fetch('http://localhost:5299/api/WorkOrder/AddWork_Order', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData)
            });

            console.log('API响应状态:', response.status);

            if (response.ok) {
                const result = await response.json();
                console.log('保存成功，返回数据:', result);
                
                // 检查关键字段是否为空
                const emptyFields = [];
                if (!result.production_Number) emptyFields.push('production_Number');
                if (!result.article_Id) emptyFields.push('article_Id');
                if (!result.articleName) emptyFields.push('articleName');
                if (!result.activity_Id) emptyFields.push('activity_Id');
                if (!result.activity_ListNumber) emptyFields.push('activity_ListNumber');
                if (!result.planned_Start) emptyFields.push('planned_Start');
                if (!result.planned_Completion) emptyFields.push('planned_Completion');
                if (!result.planned_Output) emptyFields.push('planned_Output');
                
                if (emptyFields.length > 0) {
                    console.warn('以下字段在保存后为空:', emptyFields);
                    alert(`工单保存成功，但以下字段为空：${emptyFields.join(', ')}。请检查后端API是否正确处理这些字段。`);
                } else {
                    alert('工单保存成功！');
                }
                
                // 跳转到工单显示页面
                window.location.href = '/Home/OrderShow';
            } else {
                const errorText = await response.text();
                console.error('保存失败:', response.status, errorText);
                alert('保存失败：' + (errorText || response.statusText));
            }
        } catch (error) {
            console.error('保存错误:', error);
            alert('保存失败：' + error.message);
        } finally {
            // 恢复按钮状态
            const saveBtn = document.getElementById('saveWorkOrder');
            saveBtn.innerHTML = '<i class="fas fa-save"></i> 保存';
            saveBtn.disabled = false;
        }
    }

    // 通过工序编码获取工序ID（当返回数据中没有直接带出ID时使用）
    async function resolveActivityIdByNumber(activityNo) {
        if (!activityNo) return 0;
        try {
            const resp = await fetch('http://localhost:5299/api/WorkOrder/GetActivity_ListOutput');
            if (!resp.ok) return 0;
            const data = await resp.json();
            const list = Array.isArray(data?.pageData) ? data.pageData : Array.isArray(data?.data) ? data.data : [];
            const found = list.find(x => (x.activity_ListNumber || x.Activity_ListNumber) === activityNo);
            const id = found?.id ?? found?.Id ?? found?.activity_Id ?? found?.Activity_Id ?? found?.activityId ?? 0;
            return parseInt(id, 10) || 0;
        } catch { return 0; }
    }

    // 重置表单
    function resetForm() {
        if (confirm('确定要重置表单吗？所有数据将被清空。')) {
            document.querySelector('form').reset();
            // 清空工序表格
            document.querySelector('#processTable tbody').innerHTML = '';
            processCounter = 1;
            // 重新生成工单编号
            generateOrderCode();
            setCurrentDate();
        }
    }

    // 绑定事件
    document.getElementById('saveWorkOrder').addEventListener('click', saveWorkOrder);
    document.getElementById('resetForm').addEventListener('click', resetForm);
</script>
